<template>
  <div class="item-container">
    <!-- 查询表单 -->
    <el-form
      ref="queryFormRef"
      :model="queryParams"
      :inline="true"
      label-width="80px"
    >
      <el-form-item label="商品名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品编码" prop="itemCode">
        <el-input
          v-model="queryParams.itemCode"
          placeholder="请输入商品编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb-4">
      <el-col :span="1.5">
        <el-button type="primary" icon="Plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="Edit"
          :disabled="!hasSelected"
          @click="handleUpdate"
        >
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="Delete"
          :disabled="!hasSelected"
          @click="handleDelete"
        >
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="Download" @click="handleExport"
          >导出</el-button
        >
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="itemList"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编码" prop="itemCode" width="120" />
      <el-table-column label="商品名称" prop="itemName" show-overflow-tooltip />
      <el-table-column label="分类" prop="categoryName" width="120" />
      <el-table-column label="单位" prop="unit" width="80" />
      <el-table-column label="价格" prop="price" width="100">
        <template #default="{ row }">
          <span>¥{{ row.price || "0.00" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180" />
      <el-table-column label="操作" fixed="right" width="200">
        <template #default="{ row }">
          <el-button type="primary" link icon="View" @click="handleView(row)">
            查看
          </el-button>
          <el-button type="primary" link icon="Edit" @click="handleUpdate(row)">
            修改
          </el-button>
          <el-button
            type="danger"
            link
            icon="Delete"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      append-to-body
    >
      <el-form
        ref="itemFormRef"
        :model="itemForm"
        :rules="itemRules"
        label-width="80px"
      >
        <el-form-item label="商品名称" prop="itemName">
          <el-input v-model="itemForm.itemName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品编码" prop="itemCode">
          <el-input v-model="itemForm.itemCode" placeholder="请输入商品编码" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="itemForm.categoryId" placeholder="请选择分类">
            <el-option
              v-for="category in categoryList"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="itemForm.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="itemForm.price"
            :precision="2"
            :min="0"
            placeholder="请输入价格"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="itemForm.description"
            type="textarea"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="loading" @click="submitForm">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { 
  listItem, 
  getItem, 
  addItem, 
  updateItem, 
  delItem, 
  exportItem,
  getItemCategories 
} from "@/api/wms/item";

// 定义组件名称
defineOptions({
  name: "WmsItem",
});

// 响应式数据
const queryFormRef = ref();
const itemFormRef = ref();
const dialogVisible = ref(false);
const loading = ref(false);
const itemList = ref<any[]>([]);
const selectedItems = ref<any[]>([]);
const categoryList = ref<any[]>([]);
const total = ref(0);

// 查询参数
const queryParams = reactive({
  itemName: "",
  itemCode: "",
  pageNum: 1,
  pageSize: 10,
});

// 表单数据
const itemForm = reactive({
  id: undefined as number | undefined,
  itemName: "",
  itemCode: "",
  categoryId: 0,
  unit: "",
  price: 0,
  description: "",
});

// 表单验证规则
const itemRules = {
  itemName: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
  itemCode: [{ required: true, message: "商品编码不能为空", trigger: "blur" }],
  categoryId: [{ required: true, message: "请选择分类", trigger: "change" }],
  unit: [{ required: true, message: "单位不能为空", trigger: "blur" }],
};

// 计算属性
const hasSelected = computed(() => selectedItems.value.length > 0);
const dialogTitle = computed(() => (itemForm.id ? "修改商品" : "新增商品"));

/**
 * 获取列表数据
 */
const getList = async (): Promise<void> => {
  loading.value = true;
  try {
    const response = await listItem(queryParams);
    itemList.value = response.rows || [];
    total.value = response.total || 0;
  } catch (error) {
    ElMessage.error("获取商品列表失败");
  } finally {
    loading.value = false;
  }
};

/**
 * 搜索按钮操作
 */
const handleQuery = (): void => {
  queryParams.pageNum = 1;
  getList();
};

/**
 * 重置按钮操作
 */
const resetQuery = (): void => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/**
 * 新增按钮操作
 */
const handleAdd = (): void => {
  resetForm();
  dialogVisible.value = true;
};

/**
 * 修改按钮操作
 */
const handleUpdate = async (row?: any): Promise<void> => {
  resetForm();
  const item = row || selectedItems.value[0];
  if (!item) return;

  try {
    const detail = await getItem(item.id);
    Object.assign(itemForm, detail);
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error("获取商品详情失败");
  }
};

/**
 * 查看操作
 */
const handleView = async (row: any): Promise<void> => {
  try {
    const detail = await getItem(row.id);
    // 这里可以显示详情对话框或跳转到详情页面
    console.log("商品详情:", detail);
  } catch (error) {
    ElMessage.error("获取商品详情失败");
  }
};

/**
 * 删除按钮操作
 */
const handleDelete = (row?: any): void => {
  const items = row ? [row] : selectedItems.value;
  const ids = items.map((item) => item.id);
  const message = `是否确认删除编号为"${items.map((item) => item.itemCode).join(", ")}"的商品？`;

  ElMessageBox.confirm(message, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await delItem(ids);
      ElMessage.success("删除成功");
      await getList();
    } catch (error) {
      ElMessage.error("删除失败");
    }
  });
};

/**
 * 导出按钮操作
 */
const handleExport = async (): Promise<void> => {
  try {
    await exportItem(queryParams);
    ElMessage.success("导出成功");
  } catch (error) {
    ElMessage.error("导出失败");
  }
};

/**
 * 表格选择改变
 */
const handleSelectionChange = (selection: any[]): void => {
  selectedItems.value = selection;
};

/**
 * 提交表单
 */
const submitForm = (): void => {
  itemFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;

    try {
      if (itemForm.id) {
        await updateItem(itemForm);
        ElMessage.success("修改成功");
      } else {
        await addItem(itemForm);
        ElMessage.success("新增成功");
      }
      dialogVisible.value = false;
      await getList();
    } catch (error) {
      ElMessage.error(itemForm.id ? "修改失败" : "新增失败");
    }
  });
};

/**
 * 重置表单
 */
const resetForm = (): void => {
  Object.assign(itemForm, {
    id: undefined,
    itemName: "",
    itemCode: "",
    categoryId: 0,
    unit: "",
    price: 0,
    description: "",
  });
  itemFormRef.value?.resetFields();
};

/**
 * 获取分类列表
 */
const getCategoryList = async (): Promise<void> => {
  try {
    const response = await getItemCategories();
    categoryList.value = response || [];
  } catch (error) {
    console.error("获取分类列表失败:", error);
  }
};

// 组件挂载时执行
onMounted(() => {
  getList();
  getCategoryList();
});
</script>

<style lang="scss" scoped>
.item-container {
  padding: 20px;
}

.mb-4 {
  margin-bottom: 16px;
}
</style>
